/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package crawler.admin.controller;

/**
 *
 * @author ngotandieu
 */

import crawler.common.CommonUtil;
import crawler.common.RenderModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminIndexController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminIndexController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if(!CommonUtil.checkSession(req, resp))
                return;
            
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminIndexController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();

        try {
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Dashboard");
            
            
            Template template = RenderModel.getAdminCTemplate("index_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminIndexController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
}
